import sys

from loguru import logger

from app.core.config import settings
from app.core.middlewares import request_context


def logger_filter(record) -> bool:
    record["extra"]["request_id"] = request_context.get("request_id")
    record["extra"]["request_ip"] = request_context.get("request_ip")
    record["extra"]["request_method"] = request_context.get("request_method")
    record["extra"]["request_path"] = request_context.get("request_path")
    return True


def log_init():
    format_ = (
        "<g>[{time:YYYY-MM-DD HH:mm:ss.SSS}</g>][<lvl>{level}</lvl>]"
        "[{thread.name}][{name}:{function}:{line}]"
        "<c>[{extra[request_id]}|{extra[request_ip]}|{extra[request_method]}|{extra[request_path]}]</c>"
        " - <lvl>{message}</lvl>"
    )
    logger.configure(
        extra={
            "request_id": "-",
            "request_ip": "-",
            "request_method": "-",
            "request_path": "-",
        }
    )
    logger.remove()
    logger.add(
        sys.stderr,
        format=format_,
        filter=logger_filter,
        backtrace=True,
        diagnose=settings.debug,
    )
